/**
 * Page Json Jquery plugin
 *
 * @author KeiMOon
 * @version 1.2.5 (Feb 22 2010)
 * @requires Jquery 1.2.7 and laters
 *
 * Dual licensed under the MIT and LGPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/lgpl.html
 */

(function($){
    $.addPage = function(t, options) {
        if (t.page) return false; //The page has existed

        var settings = $.extend({
            url : false,
            type : "post",
            errorMessage : "No data",
            admin : false,
            currentPage : 1,
            contentFormat : 'ul', // or p
            formFunctions : [],
            onSuccess : false
        }, options||{});

        w = $(t); //jQuerify it
        var page = {                     //The page 
            init: function() {
                w.addClass("pagejson");
                this.getData();
            },
            changePage: function(type) {
                switch (type) {
                    case "first":
                        settings.currentPage = 1;
                        break;
                    case "last":
                        if (settings.total != undefined) {
                            settings.currentPage = settings.total;
                        }
                        else {
                            settings.currentPage = 1;
                        }
                        break;
                    case "prev":
                        settings.currentPage--;
                        break;
                    case "next":
                        settings.currentPage++;
                        break;

                }
                this.getData();
            },
            clear: function() {
                w.html("");
            },
            getData: function() {
                if (settings.url == false) {
                    this.buildError();
                    return;
                }
                else {
                    $(".pagejson-pre-load").show();
                    this.clear();
                    var send = {
                        page: settings.currentPage,
                        admin: settings.admin
                    };
                    send = $.param(send);
                    $.ajax({
                        url : settings.url,
                        type : settings.type,
                        data : send,
                        dataType: 'json',
                        success: function(data) {
                            $(".pagejson-pre-load").hide();
                            if (data.code == 0) {
                                page.buildError(data.message);
                                return;
                            }
                            settings.total = data.total;
                            if (settings.admin) {
                                page.buildAdmin(data);
                            }
                            else {
                                page.buildNormal(data);
                            }
                            $.each(settings.formFunctions, function(i, row){
                                $(row.selector).click(function(){
                                    return row.func(this);
                                });
                            });
                            if (settings.onSuccess) {
                                settings.onSuccess();
                            }
                            
                        },
                        error: function() {
                            page.buildError(settings.errorMessage);
                            $(".pagejson-pre-load").hide();
                        }
                    });
                }
            },
            buildNormal: function(data) {
                if (data.rows.length == 0) {
                    this.buildError(data.message);
                    return;
                }
                else {
                    this.buildContent(data);
                    if (data.hasTab) {
                        this.buildTab(data);
                    }
                    this.buildPagination(data);
                }
            },
            buildAdmin: function(data) {
                if (data.rows.length == 0) {
                    this.buildError(data.message);
                    return;
                }
                else {
                    this.buildContent(data);
                    if (data.hasTab) {
                        this.buildTab(data);
                    }
                    this.buildPagination(data);
                    this.buildForm(data);
                }
            },
            buildError: function(errorMessage) {
                w.html("<p class=\"error\">" + errorMessage + "</p>");
            },
            buildContent: function(data) {
                var rowDiv;
                var rowHeaderDiv;
                var rowFooterDiv;
                var contentDiv;
                var contentMainDiv;
                var contentMainHeaderDiv;
                var controlDiv;
                var contentUl;
                var contentLi;
                var contentElementDiv;
                $.each(data.rows, function(i, row){
                    rowDiv = document.createElement("div");
                    w.append(rowDiv);
                    $(rowDiv).addClass("pagejson-row");

                    rowHeaderDiv = document.createElement("div");
                    $(rowDiv).append(rowHeaderDiv);
                    $(rowHeaderDiv).addClass("pagejson-row-header");
                    $(rowHeaderDiv).html('<span></span>');
                    
                    contentDiv = document.createElement("div");
                    $(rowDiv).append(contentDiv);
                    $(contentDiv).addClass("pagejson-content");

                    contentMainDiv = document.createElement("div");
                    $(contentDiv).append(contentMainDiv);
                    $(contentMainDiv).addClass("pagejson-main");

                    if (data.hasHeader) {
                        contentMainHeaderDiv = document.createElement("div");
                        $(contentMainDiv).append(contentMainHeaderDiv);
                        $(contentMainHeaderDiv).addClass("pagejson-main-header").html(row.header);
                    }

                    controlDiv = document.createElement("div");
                    $(rowDiv).append(controlDiv);
                    $(controlDiv).addClass("pagejson-control");

                    rowFooterDiv = document.createElement("div");
                    $(rowDiv).append(rowFooterDiv);
                    $(rowFooterDiv).addClass("pagejson-row-footer");
                    $(rowFooterDiv).html('<span></span>');

                    if (settings.contentFormat == 'ul') {
                        contentUl = document.createElement("ul");
                        $(contentMainDiv).append(contentUl);
                    }
                    
                    $.each(row.content, function(j, value){
                        if (settings.contentFormat == 'ul') {
                            contentLi = document.createElement("li");
                            $(contentUl).append(contentLi);
                            $(contentLi).html(value);
                        }
                        else {
                            contentElementDiv = document.createElement("div");
                            $(contentMainDiv).append(contentElementDiv);
                            $(contentElementDiv).html(value);
                        }
                    });
                });
            },
            buildTab: function(data) {
                var controlText = $.extend({
                    detail : "Detail",
                    noData : "No data"
                }, data.controlText||{});
                
                var tabAnchor = document.createElement("a");
                $(tabAnchor).addClass("pagejson-control-tab").attr('href', '#').html("<span>" + controlText.detail + "</span>");
                w.find(".pagejson-control").append(tabAnchor);

                var tabMainDiv = document.createElement("div");
                $(tabMainDiv).addClass("pagejson-tab");
                w.find(".pagejson-row").append(tabMainDiv);

                var tabHeaderDiv = document.createElement("div");
                $(tabHeaderDiv).addClass("pagejson-tab-header");
                w.find(".pagejson-tab").append(tabHeaderDiv);

                var tabHeaders = w.find(".pagejson-tab-header");
                var tabHeaderUl;
                var tabHeaderLi;
                var tabContentDiv;
                var tabContentRowDiv;
                var tabContentUl;
                var tabContentLi;
                var tabContentP;

                $.each(tabHeaders, function(i, tabHeader){
                    tabHeaderUl = document.createElement("ul");
                    $(tabHeader).append(tabHeaderUl);

                    tabContentDiv = document.createElement("div");
                    $(tabContentDiv).addClass("pagejson-tab-content");
                    $(tabHeader).parent().append(tabContentDiv);

                    var tabNum = 1;

                    $.each(data.rows[i].tab, function(tabKey, tabValue){
                        //Header
                        tabHeaderLi = document.createElement("li");
                        $(tabHeaderUl).append(tabHeaderLi);
                        $(tabHeaderLi).attr("rel", "tab-" + tabNum);
                        $(tabHeaderLi).html("<a href=\"#\">" + tabKey + "</a>");

                        //Content
                        tabContentRowDiv  = document.createElement("div");
                        $(tabContentRowDiv).addClass("pagejson-tab-content-row").addClass("tab-" + tabNum);
                        $(tabContentDiv).append(tabContentRowDiv);

                        if (tabValue.length == 0) {
                            $(tabContentRowDiv).html(controlText.noData);
                        }
                        else {
                            if (settings.contentFormat == 'ul') {
                                tabContentUl = document.createElement("ul");
                                $(tabContentRowDiv).append(tabContentUl);
                            }

                            $.each(tabValue, function(j, tabRow){
                                if (settings.contentFormat == 'ul') {
                                    tabContentLi = document.createElement("li");
                                    $(tabContentUl).append(tabContentLi);
                                    $(tabContentLi).html(tabRow);
                                }
                                else {
                                    tabContentP = document.createElement("p");
                                    $(tabContentRowDiv).append(tabContentP);
                                    $(tabContentP).html(tabRow);
                                }
                            });
                            if (tabNum > 1) {
                                $(tabContentRowDiv).hide();
                            }
                            else {
                                $(tabHeaderLi).addClass("current");
                            }
                        }
                        tabNum++;
                    });    
                });
                $(".pagejson-tab").hide();
                $(".pagejson-control-tab a").bind("click", function(){
                    $(this).parent().parent().parent().find(".pagejson-tab").toggle();
                    return false;
                });

                $(".pagejson-tab-header li a").bind("click", function(){
                    var rel = $(this).parent().attr("rel");
                    $(this).parent().parent().find("li").removeClass("current");
                    $(this).parent().addClass("current");
                    $(this).parent().parent().parent().parent().find(".pagejson-tab-content-row").hide();
                    $(this).parent().parent().parent().parent().find("." + rel).show();
                    return false;
                });
            },
            buildPagination: function(data) {
                if (data.total <= 1) {
                    return;
                }
                var controlText = $.extend({
                    prev: "Prev",
                    next: "Next",
                    first: "First",
                    last: "Last"
                }, data.controlText||{});

                var paginationDiv = document.createElement("div");
                $(paginationDiv).addClass("pagejson-pagination");
                w.append(paginationDiv);
                
                var firstSpan = document.createElement("span");
                $(firstSpan).addClass("pagejson-pagination-first").html("<a href=\"#\">" + controlText.first + "</a>");
                $(paginationDiv).append(firstSpan);

                var prevSpan = document.createElement("span");
                $(prevSpan).addClass("pagejson-pagination-prev").html("<a href=\"#\">" + controlText.prev + "</a>");
                $(paginationDiv).append(prevSpan);

                var nextSpan = document.createElement("span");
                $(nextSpan).addClass("pagejson-pagination-next").html("<a href=\"#\">" + controlText.next + "</a>");
                $(paginationDiv).append(nextSpan);

                var lastSpan = document.createElement("span");
                $(lastSpan).addClass("pagejson-pagination-last").html("<a href=\"#\">" + controlText.last + "</a>");
                $(paginationDiv).append(lastSpan);

                var clearDiv = document.createElement("div");
                $(clearDiv).css("clear", "both");
                $(paginationDiv).append(clearDiv);

                if (settings.currentPage <= 1) {
                    $(".pagejson-pagination-prev, .pagejson-pagination-first").css("visibility", "hidden");
                }

                if (settings.currentPage >= data.total) {
                    $(".pagejson-pagination-next, .pagejson-pagination-last").css("visibility", "hidden")
                }

                

                $(".pagejson-pagination-first a").bind("click",function(){
                    page.changePage("first");
                    return false;
                });
                $(".pagejson-pagination-prev a").bind("click",function(){
                    page.changePage("prev");
                    return false;
                });
                $(".pagejson-pagination-next a").bind("click",function(){
                    page.changePage("next");
                    return false;
                });
                $(".pagejson-pagination-last a").bind("click",function(){
                    page.changePage("last");
                    return false;
                });
            },
            buildForm: function(data) {
                var controlText = $.extend({
                    closeForm : "Close"
                }, data.controlText||{});
                
                var formDiv = document.createElement("div");
                $(formDiv).addClass("pagejson-form");
                $(".pagejson-content").append(formDiv);

                var formCloseAnchor;
                
                $.each($(".pagejson-form"), function(i, rowForm){
                    var formControlAnchor;
                    var formNum = 1;
                    var formRowDiv;
                    $.each(data.rows[i].form, function(key, value){
                        formControlAnchor = document.createElement("a");
                        $(formControlAnchor).addClass("pagejson-control-form").attr("rel", "form-row-" + formNum).attr('href', '#').html("<span>" + key + "</span>");
                        $(rowForm).parent().parent().find(".pagejson-control").append(formControlAnchor);

                        formRowDiv = document.createElement("div");
                        $(formRowDiv).addClass("pagejson-form-row").addClass("form-row-" + formNum).html(value);
                        $(rowForm).append(formRowDiv);

                        $(formRowDiv).hide();
                        formNum++;
                    });
                    formCloseAnchor = document.createElement("a");
                    $(formCloseAnchor).addClass("pagejson-control-form-close").html("<span>" + controlText.closeForm + "</span>").attr('href', '#');
                    $(rowForm).parent().parent().find(".pagejson-control").append(formCloseAnchor);
                    $(formCloseAnchor).hide();
                });

                
                
                $(".pagejson-control-form").bind("click", function(){
                    $(this).parent().parent().find(".pagejson-form-row").hide();
                    $(this).parent().parent().find(".pagejson-main").hide();
                    var rel = $(this).attr("rel");
                    $(this).parent().parent().find("." + rel).show();
                    $(this).parent().find('.pagejson-control-form-close').show();
                    return false;
                });

                $(".pagejson-control-form-close").bind("click", function(){
                    $(this).parent().parent().find(".pagejson-form-row").hide();
                    $(this).parent().parent().find(".pagejson-main").show();
                    $(this).hide();
                    return false;
                });
            }
        };

        t.page = page;
        t.settings = settings;
        return page.init();
    };
})(jQuery);

(function($) {
    var docloaded = false;

    $(document).ready(function () {
        docloaded = true
    } );

    $.fn.pageJson = function(options) {

        return this.each( function() {
            if (!docloaded)
            {
                $(this).hide();
                var t = this;
                $(document).ready
                (
                    function ()
                    {
                        $.addPage(t, options);
                    }
                    );
            } else {
                $.addPage(this, options);
            }
        });

    };

    $.fn.pageJsonRefresh = function(to) {
        return this.each(function(){
            if (this.page && this.settings.url) {
                if (to == false) {
                    this.page.getData();
                }
                else {
                    this.page.changePage(to);
                }
            }
        });
    };

})(jQuery);

